﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.EmailProvider;
//using System.Web.Mail;
using System.Net.Mail;
using BSCMFF.Core.Exceptions.Database;
using Telerik.Web.UI;
using BSCMFF.Web.UserControls.Selections;
using BSCMFF.Core;
using System.Drawing;

namespace BSCMFF.Web.Pages.Evaluation_Setup.Personalist
{
    /// <summary>
    /// Manages email notifications.
    /// </summary>
    /// <remarks></remarks>
    public partial class Notifications : MultiLanguagePage
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void Page_Load(object sender, EventArgs e)
        {
            RadGridNotifications.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;

            if (IsPostBack && EvalSelection.PublicSelectedValue != 0)
            {
                PanelNotifications.Visible = true;
                                
            }
            LabelStatus.Text = "";
        }

        /// <summary>
        /// Handles the Click event of the RadButtonSendNotifications control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadButtonSendNotifications_Click(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();            
                
            Evaluation_Period ep = (from eps in context.Evaluation_Period
                                    where eps.ID == EvalSelection.PublicSelectedValue
                                    select eps).SingleOrDefault();
            if (ep != null)
            {
                string subject = "BSCMFF Evaluation Period Notification";
                string body = "Evaluation period - " + ep.Name + "<br /> Start Date: " + ep.StartDate.ToShortDateString()
                                                                + "<br /> End Date: " + ep.EndDate.ToShortDateString();

                try
                {
                    SendEmailToAssignedEmployeesNow(EvalSelection.PublicSelectedValue, subject, body);
                    LabelStatus.Text = "Emails were successfully sent.";
                    LabelStatus.ForeColor = Color.Green;
                }
                catch (Exception ex)
                {
                    LabelStatus.Text = "There was a problem with sending emails : " + ex.Message;
                    LabelStatus.ForeColor = Color.Red;
                }
            }
            
        }

        /// <summary>
        /// Sends the email to assigned employees now.
        /// </summary>
        /// <param name="evalID">The eval ID.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <remarks></remarks>
        private void SendEmailToAssignedEmployeesNow(int evalID, string subject, string body)
        {
            BSCEntities context = new BSCEntities();

            List<string> employeesEmail = (from eee in context.Evaluation_Evaluator_Employee.Include("User")
                                           where eee.Evaluation_FK == evalID
                                           select eee.User.Email).Distinct().ToList();

            List<string> evaluatorsEmail = (from eee in context.Evaluation_Evaluator_Employee.Include("User1")
                                            where eee.Evaluation_FK == evalID
                                            select eee.User1.Email).Distinct().ToList();

            List<string> emails = employeesEmail.Union(evaluatorsEmail).ToList();

            EmailProvider.SendEmails(emails, subject, body);
            
        }

        /// <summary>
        /// Handles the UpdateCommand event of the RadGridNotifications control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Web.UI.GridCommandEventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadGridNotifications_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            BSCEntities context = new BSCEntities();

            //form = editedItem.FindControl(GridEditFormItem.EditFormUserControlID);
            int enID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

            Evaluation_Notifications en = (from ens in context.Evaluation_Notifications
                                           where ens.ID == enID
                                           select ens).SingleOrDefault();

            int days = (int)((RadNumericTextBox)editedItem.FindControl("RadNumericTextBoxDays")).Value;
            string before = ((EvalNotificationStartOrEnd)editedItem.FindControl("EvaluationStartOrEnd")).PublicSelectedValue;

            en.DaysBefore = days;
            en.StartOrEnd = before;

            Evaluation_Period ep = (from eps in context.Evaluation_Period
                                    where eps.ID == EvalSelection.PublicSelectedValue
                                    select eps).SingleOrDefault();

            if (en.StartOrEnd == "Start")
            {
                en.DateToSend = ep.StartDate.AddDays(en.DaysBefore * (-1));
            }
            if (en.StartOrEnd == "End")
            {
                en.DateToSend = ep.EndDate.AddDays(en.DaysBefore * (-1));
            }

            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't update Notification :" + ex.Message);
            }
        }

        /// <summary>
        /// Handles the InsertCommand event of the RadGridNotifications control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Web.UI.GridCommandEventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadGridNotifications_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            BSCEntities context = new BSCEntities();
            
            Evaluation_Notifications en = new Evaluation_Notifications();
            en.Evaluation_Period_FK = EvalSelection.PublicSelectedValue;
            en.Sent = false;

            int days = (int)((RadNumericTextBox)editedItem.FindControl("RadNumericTextBoxDays")).Value;
            string before = ((EvalNotificationStartOrEnd)editedItem.FindControl("EvaluationStartOrEnd")).PublicSelectedValue;

            en.DaysBefore = days;
            en.StartOrEnd = before;

            Evaluation_Period ep = (from eps in context.Evaluation_Period
                                    where eps.ID == EvalSelection.PublicSelectedValue
                                    select eps).SingleOrDefault();

            if (en.StartOrEnd == "Start")
            {
                en.DateToSend = ep.StartDate.AddDays(en.DaysBefore * (-1));
            }
            if (en.StartOrEnd == "End")
            {
                en.DateToSend = ep.EndDate.AddDays(en.DaysBefore * (-1));
            }

            context.AddToEvaluation_Notifications(en);

            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't insert Notification :" + ex.Message);
            }
        }

        /// <summary>
        /// Handles the DeleteCommand event of the RadGridNotifications control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Web.UI.GridCommandEventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadGridNotifications_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            BSCEntities context = new BSCEntities();
            int enID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

            Evaluation_Notifications en = (from ens in context.Evaluation_Notifications
                                           where ens.ID == enID
                                           select ens).SingleOrDefault();

            context.DeleteObject(en);

            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't delete Notification :" + ex.Message);
            }
        }
    }
}